//
//  VideoPlayModel.swift
//  Motion
//
//  Created by 悦月越悦 on 2021/3/21.
//

import Foundation
import Alamofire

struct Course:Decodable{
    var courseId: Int
    var courseName: String
    var backgroundUrl: String
    var actions: String
    var bodyPart: String
    var degree: String
    var duration: String
    var hits: Int
    var calorie: Int
    var courseIntro: String
    var actionList: [Action1]
}

struct Action1:Decodable{
    var actionId: Int
    var actionName: String
    var actionImgs: String
    var actionUrl: String
    var duration:String
    var intro: String
    var type:Int
    var size: Double
    var count: Int //单个视频里的动作数量
    var total: Int //总数
    var restDuration: Int
}

class VideoPlayModel: ObservableObject{
    //变量
    @Published var actionList : [Action1] = []{
        didSet{
            if(actionList.count>=1){
                curAction = actionList[0]
            }
            
            if(actionList.count >= 2){
                nAction = actionList[1]
            }
        }
    }
    @Published var relatedId : Int = 2
    @Published var urls:[URL] = []
    @Published var curIndex: Int = 0{
        didSet{
            curAction = actionList[curIndex]

            if(curIndex + 1<actionList.count){
                nAction = actionList[curIndex+1]
            }else{
                nAction = nil
            }
        }
    }
    @Published var play: Bool = true
    
    //为了循环播放♻️
    @Published var autoPlay: Bool = true
    @Published var curTimes: Int = 0
    
    //为了提示
    //时间提示
    @Published var tipBtn:Bool = false
    @Published var nextActionName: String = ""
    @Published var hasNotSetTip = true
    
    //为了进度条
    @Published var aVideoDuration: Double = 0
    @Published var per:Double = 0.0
    @Published var totalDuration:Double = 0.0
    
    //提供一些必要的信息
    @Published var curAction: Action1? = nil
    @Published var nAction: Action1? = nil
    
    //为了动作详情显示
    @Published var isPresented:Bool = false{
        didSet{
            if(isPresented == false){
                play = true
            }else{
                play = false
            }
        }
    }
    @Published var dragEnabled:Bool = true
    @Published var actionDetailModel:  ActionDetailModel = ActionDetailModel()
    
    //是否完成播放
    @Published var complete:Bool = false
    @Published var aVideoComplete:Bool = false
    
    //是否跳转到休息页面
    @Published var restPresent:Bool = false
    @Published var preparePresent:Bool = false
    
    var total :Int{
        return actionList.count
    }
    
    var totalTimes: Int{
        return actionList[curIndex].total / actionList[curIndex].count
    }
    //拉取动作视频
    func fetchVideoList(){
        let headers: HTTPHeaders = [
           "Content-Type": "application/json"
       ]
        
        let parameters = [
            "courseId": relatedId,
        ]
        
        let request = AF.request("https://www.fastmock.site/mock/318b7fee143da8b159d3e46048f8a8b3/api/getActionCounts"
                       ,method: .get
                       ,parameters: parameters
                       ,encoding: URLEncoding.default
                       ,headers: headers
                        )
            //该如何使用
        request.responseDecodable(of: ResponseData<Course>.self) { (response) in
            print(response)
            guard let res = response.value else { return }
            switch res.status {
                case .success:
                    self.actionList = res.data.actionList
                    self.createURL()
                case .failed:
                    print("faild")
            }
        }
    }
    
    func nextActionOrRest(){
        //如果当前的动作有休息的话则休息
        if(curAction!.restDuration > 0 ){
            restPresent = true
        }else{
            nextAction()
        }
        //如果没有则next()
    }
    //播放下一条视频
    func nextAction(){
        self.curTimes = 0
        aVideoComplete = false
        
        if self.curIndex >= (self.total - 1){
            complete = true
            return
        }
        self.play = false
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
            self.curIndex+=1
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
            self.play = true
        }
        
        resetTip()
    }
    
    //播放上一条视频
    func previousAction(){
        self.curTimes = 0
        aVideoComplete = false
        
        if self.curIndex <= 0 {
            return
        }
        
        self.play = false
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
           self.curIndex -= 1
        }
          
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
            self.play = true
        }
    
        resetTip()
    }
    
    //生成视频的URL
    func createURL(){
        let root = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
                    .appendingPathComponent(
                            "Motion",
                            isDirectory: false
                    )
        
        //生成URLS
        for action in actionList {
            let cachedFile = root
                .appendingPathComponent(
                    "action_\(action.actionId).mp4",
                    isDirectory: false
                )
            urls.append(cachedFile)
        }
        
        print("urls=\(urls)")
        
    }
    
    func resetTip(){
        tipBtn = false
        hasNotSetTip = true
    }
}
